from rest_framework import serializers

from BYD_ERP.utils.get_inventory import get_inventory_by_goods
from goods_info.models import GoodsModel
from production_info.models import BomMaterialModel, BomProcessModel


class BomMaterialSerializer(serializers.ModelSerializer):
    """
        BOM生产物料的序列化
    """

    # 当前库存
    # read_only=True代表：只是用于序列化，不是反序列化
    cur_inventory = serializers.SerializerMethodField(read_only=True, help_text='在当前仓库中的库存')

    class Meta:

        model = BomMaterialModel
        fields = '__all__'

    def get_cur_inventory(self, obj: BomMaterialModel):
        # 当前obj是：BomMaterialModel对象
        result = get_inventory_by_goods(obj.goods.id)
        # 如果result有就返回result，如果result没有就返回0。
        return result if result else 0

class BomProcessSerializer(serializers.ModelSerializer):
    """
        BOM生产工序的序列化
    """

    class Meta:

        model = BomProcessModel
        fields = '__all__'

class GoodsBomSerializer(serializers.ModelSerializer):
    """
        某一个货品的BOM表数据的序列化
    """

    # many=True意思是说，它是个清单/列表
    # read_only=True只需要序列化，不需要反序列化
    bom_material_list = BomMaterialSerializer(many=True, read_only=True)
    bom_process_list = BomProcessSerializer(many=True, read_only=True)

    class Meta:

        model = GoodsModel
        fields = ['id', 'specification', 'model_number', 'partner_name', 'bom_material_list', 'bom_process_list']
        # 前面四项可以直接从GoodsModel获取，后面两项不行，就需要单独写一下，就是本序列化“class Meta:”前面两项
        # bom_material_list来自于模型类BomMaterialModel中外键parent_goods中的related_name='bom_material_list'
        # bom_process_list来自于模型类BomProcessModel中外键parent_goods中的related_name='bom_process_list'